282. Expression Add Operators
282. Expression Add Operators
Description
Solution
Use tricky DFS to solve it.
The most important trick: Because we need to give each expression that leads to the target, so we need to record current string. Then, for+
and -
, in fact we just need to record the exep value
in previous expression. But to treat *
rightly, we need record one more variable – lastValue to calculate the expression rightly.
So if we have, for example 1 2 3 4 5 6 7 8
1 | 1 + 2 * 3 DFS(45678) |
↑
To treat this 2 * 3 correctly, we need first record 1 + 2
= 3, then use 3 - 2 + 2 * 3
to get the right answer.
Code
1 | class Solution { |
All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.